package com.zjl.Zookeeper.第03章_访问;

import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;
import org.junit.Test;

import java.io.IOException;
import java.util.List;

public class C2_zk监控 {
    private static ZooKeeper getZooKeeper() throws IOException {
        // ZooKeeper服务器地址和端口  connectString的值不能有空格
        //String connectString = "82.157.71.243:2181,82.157.71.243:2181,82.157.71.243:2181";
        String connectString = "82.157.71.243:2181"; // ZooKeeper服务器地址和端口
        int sessionTimeout = 2000; // 会话超时时间（毫秒）
        ZooKeeper zooKeeper = new ZooKeeper(connectString, sessionTimeout,
                event -> {
                    // 这里可以处理 WatchedEvent  如果在操作ZooKeeper时，设置了监听，则改动时会执行
                    System.out.println("Received event: " + event);
                }
        );
        return zooKeeper;
    }

    @Test//查询节点下的节点信息  监听
    public void ls_true() throws Exception {
        ZooKeeper zooKeeper = getZooKeeper();
        //第一个参数:节点路径   第二参数:是否开启监听 开启监听会使 连接zk处进行执行
        List<String> children = zooKeeper.getChildren("/", true);

        children.forEach(System.out::println);

        Thread.sleep(100000);
    }
    @Test//查询节点下的节点信息  监听
    public void getChildren() throws Exception {
        ZooKeeper zooKeeper = getZooKeeper();
        //获取当前节点的版本号
        Stat stat = zooKeeper.exists("/xxxxx",false);
        if(stat == null){
            System.out.println("不存在");
        }else{
            byte[] data = zooKeeper.getData("/xxxxx", false, stat);
            System.out.println(new String(data));
        }
    }
}
